package com.lb.jwitter.util;


import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {
	
	public static Boolean send(String tomail, String subject, String content) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("vietnguyen3107@gmail.com","vi3tki3m2004");
				}
			});

		try {

			Message message = new MimeMessage(session);
			message.setHeader("Content-Type", "text/plain; charset=UTF-8");
			
			message.setFrom(new InternetAddress("vietnguyen3107@gmail.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(tomail));
			
			message.setSubject(subject);
			
			// Create a message part to represent the body text
			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setContent( content, "text/html; charset=utf-8" ); // <----

			// use a MimeMultipart as we need to handle the file attachments
			Multipart multipart = new MimeMultipart();

			// add the message body to the mime message
			multipart.addBodyPart( messageBodyPart );

			// Put all message parts in the message
			message.setContent( multipart ); 
//			message.setText(content);

			message.saveChanges();
			Transport.send(message);

			return true;

		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
		}
	}
}